/*
 * @Author: lixu lixu@puchigames.com
 * @Date: 2025-01-03 16:49:48
 * @LastEditors: lixu lixu@puchigames.com
 * @LastEditTime: 2025-09-16 17:59:04
 * @FilePath: /go-helper/ixRedis/pipeline.go
 * @Description: Redis 管道操作
 */
package ixRedis

// Pipeline 管道操作
func (c *Client) Pipeline() *Pipeline {
	return &Pipeline{
		client: c,
		cmds:   make([]*Command, 0),
	}
}

// Command 命令结构
type Command struct {
	cmd  string
	args []interface{}
}

// Pipeline 管道结构
type Pipeline struct {
	client *Client
	cmds   []*Command
}

// Add 添加命令到管道
func (p *Pipeline) Add(cmd string, args ...interface{}) *Pipeline {
	p.cmds = append(p.cmds, &Command{
		cmd:  cmd,
		args: args,
	})
	return p
}

// Exec 执行管道
func (p *Pipeline) Exec() ([]interface{}, error) {
	if len(p.cmds) == 0 {
		return nil, nil
	}

	conn, err := p.client.getConn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// 发送所有命令
	for _, cmd := range p.cmds {
		if err := conn.Send(cmd.cmd, cmd.args...); err != nil {
			return nil, err
		}
	}

	// 刷新并获取结果
	if err := conn.Flush(); err != nil {
		return nil, err
	}

	// 接收所有结果
	results := make([]interface{}, len(p.cmds))
	for i := range results {
		results[i], err = conn.Receive()
		if err != nil {
			return nil, err
		}
	}

	return results, nil
}
